﻿namespace GreenIsomer.Data.Entities.Transform {
	using System;
	using System.Xml;
	using System.Xml.Serialization;
	using System.Globalization;

	[Serializable]
	public class TypeConversion {

		internal static void Convert(TypeConversionCollection typeConversions, XmlNodeList propertyNodes) {

			if(propertyNodes == null || propertyNodes.Count == 0) return;

			foreach(XmlNode propertyNode in propertyNodes) {
				XmlAttribute typeAttribute = propertyNode.Attributes["Type"];
				string propertyType = typeAttribute.Value;
				if(string.IsNullOrEmpty(propertyType)) continue;

				XmlAttribute originalTypeAttribute = propertyNode.OwnerDocument.CreateAttribute("gidex", "OriginalType", Settings.Namespace);
				originalTypeAttribute.Value = typeAttribute.Value;
				propertyNode.Attributes.Append(originalTypeAttribute);

				foreach(TypeConversion typeConversion in typeConversions) {
					string searchType = typeConversion.InputType;
					if(string.IsNullOrEmpty(searchType)) continue;

					if(searchType.Trim().ToUpperInvariant() == propertyType.Trim().ToUpperInvariant()) {
						typeAttribute.Value = typeConversion.OutputType;
						break;
					}
				}
			}

		}

		public TypeConversion() { }

		[XmlAttribute("InputType")]
		public string InputType { get; set; }

		[XmlAttribute("OutputType")]
		public string OutputType { get; set; }

		public override string ToString() {
			return string.Format(CultureInfo.InvariantCulture, "{0} => {1}",
				string.IsNullOrEmpty(InputType) ? "Unspecified" : InputType,
				string.IsNullOrEmpty(OutputType) ? "Unspecified" : OutputType);
		}

	}

}